import tkinter as tk
from tkinter import scrolledtext, Canvas
from zhipuai import ZhipuAI
import threading
import time

class chatAi:
    def __init__(self, page_manager):
        self.page_manager = page_manager
        self.root = page_manager.root
        self.client = ZhipuAI(api_key="2146e6eea1f11de8a04746384a63057d.jqaFY0sHt4o4zzVq")  # 替换为你的API key
        self.chat_history = []  # 存储对话记录
        
    def show(self):
        for widget in self.root.winfo_children():
            widget.destroy()
            
        main_frame = tk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        back_button = tk.Button(main_frame, text="返回", command=self.page_manager.show_main_page)
        back_button.pack(pady=10)
        
        clear_button = tk.Button(main_frame, text="清空聊天记录", command=self.clear_chat)
        clear_button.pack(pady=5)
        
        # 创建一个Frame来容纳Canvas和滚动条
        chat_container = tk.Frame(main_frame)
        chat_container.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
        
        # 创建Canvas和滚动条
        self.chat_area = tk.Canvas(chat_container, width=500, height=400, bg="white")
        scrollbar = tk.Scrollbar(chat_container, orient="vertical", command=self.chat_area.yview)
        
        # 配置Canvas的滚动
        self.chat_area.configure(yscrollcommand=scrollbar.set)
        
        # 绑定鼠标滚轮事件
        self.chat_area.bind("<MouseWheel>", self.on_mousewheel)  # Windows
        self.chat_area.bind("<Button-4>", self.on_mousewheel)    # Linux 向上滚动
        self.chat_area.bind("<Button-5>", self.on_mousewheel)    # Linux 向下滚动
        
        # 放置Canvas和滚动条
        self.chat_area.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 创建用于存放消息的Frame
        self.chat_frame = tk.Frame(self.chat_area, bg="white")
        self.chat_window = self.chat_area.create_window((0, 0), window=self.chat_frame, anchor="nw", width=self.chat_area.winfo_width())
        
        # 绑定Canvas大小变化事件
        self.chat_area.bind('<Configure>', self.on_canvas_configure)
        self.chat_frame.bind("<Configure>", lambda e: self.chat_area.configure(scrollregion=self.chat_area.bbox("all")))
        
        input_frame = tk.Frame(main_frame)
        input_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.input_box = tk.Entry(input_frame)
        self.input_box.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        send_button = tk.Button(input_frame, text="发送", command=self.send_message)
        send_button.pack(side=tk.RIGHT, padx=5)
        
        self.input_box.bind('<Return>', lambda event: self.send_message())
        
    def append_message(self, message, is_user=True):
        # 创建一个框架来容纳每条消息
        msg_frame = tk.Frame(self.chat_frame, bg="white")
        msg_frame.pack(fill=tk.X, pady=5)
        
        # 创建消息气泡
        bubble = tk.Label(msg_frame, text=message, wraplength=300, padx=10, pady=5,
                         bg="lightblue" if is_user else "lightgreen",
                         justify="left")
        
        # 根据是用户还是AI回复来决定气泡的位置
        if is_user:
            bubble.pack(side=tk.RIGHT, padx=(50, 10))  # 用户消息靠右
        else:
            bubble.pack(side=tk.LEFT, padx=(10, 50))   # AI回复靠左
        
        # 确保滚动到最新消息
        self.chat_area.update_idletasks()
        self.chat_area.yview_moveto(1.0)
        
        role = "user" if is_user else "assistant"
        self.chat_history.append({"role": role, "content": message})
        
    def send_message(self):
        message = self.input_box.get().strip()
        if not message:
            return
        
        self.append_message(message, is_user=True)
        self.input_box.delete(0, tk.END)
        
        threading.Thread(target=self.get_ai_response, args=(message,), daemon=True).start()
        
    def get_ai_response(self, message):
        try:
            self.chat_history.append({"role": "user", "content": message})
            
            response = self.client.chat.completions.create(
                model="glm-4-flash",
                messages=self.chat_history
            )
            
            ai_message = response.choices[0].message.content
            self.chat_history.append({"role": "assistant", "content": ai_message})
            
            self.root.after(0, lambda: self.append_message(ai_message, is_user=False))
            
        except Exception as e:
            self.root.after(0, lambda e=e: self.append_message(f"错误: {str(e)}", is_user=False))
            
    def clear_chat(self):
        self.chat_history = []
        for widget in self.chat_frame.winfo_children():
            widget.destroy()

    def on_canvas_configure(self, event):
        # 更新内部frame的宽度以匹配canvas
        width = event.width
        self.chat_area.itemconfig(self.chat_window, width=width)

    def on_mousewheel(self, event):
        # Windows 鼠标滚轮事件
        if event.num == 4:
            self.chat_area.yview_scroll(-1, "units")
        elif event.num == 5:
            self.chat_area.yview_scroll(1, "units")
        else:
            # Windows 使用 event.delta
            self.chat_area.yview_scroll(int(-1 * (event.delta / 120)), "units")
